#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
# import logging
# import sys

# logging.basicConfig(stream=sys.stderr, level=logging.INFO)


def job_parser(html):
    '''parse web page and return json data,
    if web page is not expected, and then return None
    '''
    try:
        bshtml = BeautifulSoup(html, "lxml")
        position_name = bshtml.find('div', class_='job-name')['title']
        tags = [el.get_text().replace('/', '').strip()
                for el in bshtml.find('dd', class_='job_request').find_all('span')]
        salary = tags[0]
        job_request = '\n'.join(tags[1:])
        job_advantage = bshtml.find(
            'dd', class_='job-advantage').p.get_text()
        job_description = '\n'.join([el.get_text() for el in bshtml.find(
            'dd', class_='job_bt').find_all('span')])
        job_address = bshtml.find(
            'dd', class_='job-address').find('div', class_='work_addr').get_text().strip().replace(' ', '').replace(u'查看地图', '').strip()
        company = bshtml.find('dl', class_='job_company')
        company_lghomepage = company.find('a')['href']
        company_name = company.find('img')['alt']
    except Exception as e:
        # logging.warning('[parser.py-job_parser]>>Parse error: %s', e)
        # 解析错误， 可能是http请求出问题
        result = None
    else:
        result = {
            "positionName": position_name,
            "salary": salary,
            "job_request": job_request,
            "info": {
                "jobAdvantage": job_advantage,
                "jobDescription": job_description
            },
            "address": job_address,
            "company": {
                "lagou_homepage": company_lghomepage,
                "name": company_name
            }
        }
    return result


def company_parser(html):
    pass
